package com.lcu.student.service.impl;

import com.lcu.Result.Result;
import com.lcu.student.entity.PageBean;
import com.lcu.student.entity.Student;
import com.lcu.student.mapper.StudentMapper;
import com.lcu.student.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 带条件的分页查询
     */
    @Override
    public Result selectByPage(int currentPage, int pageSize, Student student) {
        int begin = (currentPage - 1) * pageSize;
        int size = pageSize;

        //将数据进行处理
        String studentName = student.getStudentName();
        if (studentName != null && studentName.length() != 0) {
            student.setStudentName("%" + studentName + "%");
        }
        String studentNumber = student.getStudentNumber();
        if (studentNumber != null && studentNumber.length() != 0) {
            student.setStudentNumber("%" + studentNumber + "%");
        }

        //进行查询数据
        List<Student> row = studentMapper.selectByPage(begin, size, student);

        //将总数查出来
        int totalCount = studentMapper.selectTotalCount(student);

        //将数据存入PageBean
        PageBean<Student> pageBean = new PageBean<>();
        pageBean.setTotalCount(totalCount);
        pageBean.setRows(row);

        return Result.success(pageBean);
    }

    /**
     * 根据id删除学生数据与学生的成绩数据
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(int id, String studentNumber) {
        try {
            studentMapper.deleteById(id);
            studentMapper.deleteGradesById(studentNumber);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("404", "没有删除成功！");
    }

    /**
     * 根据ids批量删除数据
     *
     * @param ids
     * @return
     */
    @Override
    public Result deleteByIds(List<Integer> ids) {
        studentMapper.deleteByIds(ids);
        return Result.success();
    }

    /**
     * 添加数据
     *
     * @param student
     * @return
     */
    @Override
    public Result addStudent(Student student) {
        List<String> list = studentMapper.selectNumber();
        for (String s : list) {
            if (s.equals(student.getStudentNumber())) {
                return Result.error("学号重复，请重新添加！！！");
            }
        }
        studentMapper.addStudent(student);
        return Result.success();
    }

    /**
     * 修改数据
     * @param student
     * @return
     */
    @Override
    public Result updateById(Student student) {
        studentMapper.updateById(student);
        return Result.success();
    }

}
